/*=============================================================================

  Library: CFS

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/


#include "CFSException.h"

#include <typeinfo>

#include <QDebug>

// --------------------------------------------------------------------------
CFSException::TraceManipulator::TraceManipulator(const CFSException* e)
  : Exc(e)
{
}

// --------------------------------------------------------------------------
QDebug CFSException::TraceManipulator::print(QDebug dbg) const
{
  if (Exc)
    Exc->printStackTrace(dbg);
  return dbg.maybeSpace();
}

// --------------------------------------------------------------------------
CFSException::CFSException(const QString& msg)
  : Msg(msg), NestedException(0)
{
}

// --------------------------------------------------------------------------
CFSException::CFSException(const QString& msg, const CFSException& cause)
  : Msg(msg), NestedException(cause.clone())
{
}

// --------------------------------------------------------------------------
CFSException::CFSException(const CFSException& exc)
  : std::exception(exc), CFSBackTrace(exc), Msg(exc.Msg)
{
  NestedException = exc.NestedException ? exc.NestedException->clone() : 0;
}

// --------------------------------------------------------------------------
CFSException::~CFSException() throw()
{
  delete NestedException;
}

// --------------------------------------------------------------------------
CFSException& CFSException::operator=(const CFSException& exc)
{
  if (&exc != this)
  {
    delete NestedException;
    Msg = exc.Msg;
    NestedException = exc.NestedException ? exc.NestedException->clone() : 0;
  }
  return *this;
}

// --------------------------------------------------------------------------
const CFSException* CFSException::cause() const throw()
{
  return NestedException;
}

// --------------------------------------------------------------------------
void CFSException::setCause(const CFSException& cause)
{
  delete NestedException;
  NestedException = cause.clone();
}

// --------------------------------------------------------------------------
const char *CFSException::name() const throw()
{
  return "CFSException";
}

// --------------------------------------------------------------------------
const char* CFSException::className() const throw()
{
  return typeid(*this).name();
}

// --------------------------------------------------------------------------
const char* CFSException::what() const throw()
{
  if (WhatMsg.empty())
  {
    WhatMsg = std::string(name());
    if (!Msg.isEmpty())
    {
      WhatMsg += ": ";
      WhatMsg += Msg.toStdString();
    }
  }
  return WhatMsg.c_str();
}

// --------------------------------------------------------------------------
QString CFSException::message() const throw()
{
  return Msg;
}

// --------------------------------------------------------------------------
CFSException::TraceManipulator CFSException::printStackTrace() const
{
  return TraceManipulator(this);
}

// --------------------------------------------------------------------------
CFSException* CFSException::clone() const
{
  return new CFSException(*this);
}

// --------------------------------------------------------------------------
void CFSException::rethrow() const
{
  throw *this;
}

// --------------------------------------------------------------------------
QDebug CFSException::printStackTrace(QDebug dbg) const
{
  QSet<const CFSException*> dejaVu;
  dejaVu.insert(this);

  // Print our stack trace
  dbg.nospace() << this->what() << '\n';
  QList<QString> trace = stackTrace();
  foreach(QString traceElement, trace)
  {
    dbg.nospace() << "\tat " << qPrintable(traceElement) << '\n';
  }

  // Print cause, if any
  if (NestedException)
  {
    NestedException->printEnclosedStackTrace(dbg, trace, "Caused by: ", "", dejaVu);
  }
  return dbg;
}

// --------------------------------------------------------------------------
void CFSException::printEnclosedStackTrace(QDebug dbg, const QList<QString>& enclosingTrace,
                                           const QString& caption, const QString& prefix,
                                           QSet<const CFSException*>& dejaVu)
{
  if (dejaVu.contains(this))
  {
    dbg.nospace() << "\t[CIRCULAR REFERENCE:" << this->what() << "]\n";
  }
  else
  {
    dejaVu.insert(this);
    // Compute number of frames in common between this and enclosing trace
    QList<QString> trace = stackTrace();
    int m = trace.size() - 1;
    int n = enclosingTrace.size() - 1;
    while (m >= 0 && n >=0 && trace[m] == enclosingTrace[n])
    {
      m--; n--;
    }
    int framesInCommon = trace.size() - 1 - m;

    // Print our stack trace
    dbg.nospace() << qPrintable(prefix) << qPrintable(caption) << this->what() << '\n';
    for (int i = 0; i <= m; i++)
    {
      dbg.nospace() << qPrintable(prefix) << "\tat " << qPrintable(trace[i]) << '\n';
    }
    if (framesInCommon != 0)
    {
      dbg.nospace() << qPrintable(prefix) << "\t... " << framesInCommon << " more\n";
    }

    // Print cause, if any
    if (NestedException)
    {
      NestedException->printEnclosedStackTrace(dbg, trace, "Caused by: ", prefix, dejaVu);
    }
  }
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug dbg, const CFSException& exc)
{
  dbg << exc.what();
  return dbg.maybeSpace();
}

//----------------------------------------------------------------------------
QDebug operator<<(QDebug dbg, const CFSException::TraceManipulator& trace)
{
  return trace.print(dbg);
}

CFS_IMPLEMENT_EXCEPTION(CFSUnsupportedOperationException, CFSException, "CFSUnsupportedOperationException")
CFS_IMPLEMENT_EXCEPTION(CFSRuntimeException, CFSException, "CFSRuntimeException")
CFS_IMPLEMENT_EXCEPTION(CFSInvalidArgumentException, CFSRuntimeException, "CFSInvalidArgumentException")
CFS_IMPLEMENT_EXCEPTION(CFSIllegalStateException, CFSRuntimeException, "CFSIllegalStateException")
